package com.freeLearning.boot.course.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.freeLearning.boot.course.mapper.CourseChaptersMapper;
import com.freeLearning.boot.course.model.VO.CourseChaptersSortVO;
import com.freeLearning.boot.course.model.entity.CourseChapters;
import com.freeLearning.boot.course.model.entity.CourseInfo;
import com.freeLearning.boot.course.model.query.CourseChaptersPageQuery;
import com.freeLearning.boot.course.service.CourseChaptersService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
@RequiredArgsConstructor
public class CourseChaptersServiceImpl extends ServiceImpl<CourseChaptersMapper, CourseChapters> implements CourseChaptersService {

    private final CourseChaptersMapper courseChaptersMapper;

    @Override
    public IPage<CourseChapters> pageQuery(CourseChaptersPageQuery courseChaptersPageQuery) {
        // 参数构建
        int pageNum = courseChaptersPageQuery.getPageNum();
        int pageSize = courseChaptersPageQuery.getPageSize();
        Page<CourseInfo> page = new Page<>(pageNum, pageSize);
        return this.courseChaptersMapper.getPage(page, courseChaptersPageQuery);
    }

    @Override
    public boolean sortChapters(List<CourseChaptersSortVO> courseChaptersSortVOS) {
        try {
            AtomicInteger index = new AtomicInteger();
            courseChaptersSortVOS.forEach(item->{
                CourseChapters chapters = this.getById(item.getId());
                chapters.setChapterOrder(index.incrementAndGet());
                this.updateById(chapters);
            });
        }catch (Exception e){
            return false;
        }
        return true;
    }
}
